'use client'

import { useEffect, useState } from 'react'
import { VmsTopic } from '@/types/Model'
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Progress } from '@/components/ui/progress'
import { Badge } from '@/components/ui/badge'
import { Tooltip, TooltipContent, TooltipTrigger, TooltipProvider } from '@/components/ui/tooltip'
import Link from 'next/link'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import moment from 'moment'
import { Trash2, Edit } from 'lucide-react'
import { toast } from '@/hooks/use-toast'
import { useRouter } from 'next/navigation'


export default function TopicsPage() {
  const [topics, setTopics] = useState<VmsTopic[]>([])
  const [loading, setLoading] = useState(true)
  const [showForm, setShowForm] = useState(false)
  const [editTopic, setEditTopic] = useState<VmsTopic | null>(null)
  const router = useRouter()

  const fetchTopics = async () => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch('/api/topic', {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        if (response.status === 401) {
          router.push('/login')
          toast({
            title: '登录信息过期',
            description: '请重新登录',
            variant: 'destructive'
          })
          localStorage.clear()
          return
        }
      }
      
      const data = await response.json()
      // Sort by created date descending with null check
      const sortedData = data.sort((a: VmsTopic, b: VmsTopic) => {
        const dateA = a.cjsj ? new Date(a.cjsj).getTime() : 0;
        const dateB = b.cjsj ? new Date(b.cjsj).getTime() : 0;
        return dateB - dateA;
      })
      setTopics(sortedData)
      toast({
        title: '数据获取成功',
        description: '话题列表已更新',
      })
    } catch (error) {
      console.error('Error fetching topics:', error)
      toast({
        title: '数据获取失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchTopics()
  }, [])

  const handleDelete = async (id: string) => {
    try {
      const token = localStorage.getItem('token')
      if (!id) {
        throw new Error('Topic ID is required for deletion')
      }
      const response = await fetch(`/api/topic/${id}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        throw new Error('Failed to delete topic')
      }
      
      // Optimistic update instead of refetching
      setTopics(prev => prev.filter(topic => topic.id !== id))
      toast({
        title: '删除成功',
        description: '话题已删除',
      })
    } catch (error) {
      console.error('Error deleting topic:', error)
      toast({
        title: '删除失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
      // Revert if error occurs
      fetchTopics()
    }
  }

  const handleEdit = (topic: VmsTopic) => {
    setEditTopic(topic)
    setShowForm(true)
  }

  const handleSubmit = async (topic: VmsTopic) => {
    try {
      const token = localStorage.getItem('token')
      const method = topic.id ? 'PUT' : 'POST'
      const url = topic.id ? `/api/topic` : '/api/topic'
 
    // 双重检查确保 status 不为空
    if (!topic.status || topic.status.trim() === '') {
      topic.status = 'To Do'
    }
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(topic)
      })
      
      if (!response.ok) {
        throw new Error(`Failed to ${topic.id ? 'update' : 'create'} topic`)
      }
      
      const updatedTopic = await response.json()
      
      // Optimistic update
      if (topic.id) {
        setTopics(prev => 
          prev.map(t => t.id === topic.id ? updatedTopic : t)
        )
        toast({
          title: '更新成功',
          description: '话题已更新',
        })
      } else {
        setTopics(prev => [updatedTopic, ...prev])
        toast({
          title: '创建成功',
          description: '新话题已创建',
        })
      }
      
      setShowForm(false)
      setEditTopic(null)
    } catch (error) {
      console.error('Error submitting topic:', error)
      toast({
        title: '操作失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
      // Revert if error occurs
      fetchTopics()
    }
  }

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
      </div>
    )
  }

  return (
    <TooltipProvider>
      <div className="container mx-auto py-10">
        <div className="flex justify-between items-center mb-4">
          <h1 className="text-2xl font-bold">Topics</h1>
          <Button onClick={() => setShowForm(true)}>Add Topic</Button>
        </div>

        <Dialog open={showForm} onOpenChange={(open: boolean) => {
          if (!open) {
            setShowForm(false)
            setEditTopic(null)
          }
        }}>
          <DialogContent className="sm:max-w-[425px]">
            <DialogHeader>
              <DialogTitle>{editTopic ? '编辑话题' : '新建话题'}</DialogTitle>
            </DialogHeader>
            <TopicForm 
              onCancel={() => {
                setShowForm(false)
                setEditTopic(null)
              }}
              onSubmit={handleSubmit}
              topic={editTopic}
            />
          </DialogContent>
        </Dialog>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {topics?.map((topic) => {
            const createdDate = topic.cjsj ? moment(topic.cjsj).format('YYYY-MM-DD') : 'N/A'
            const copyProgress = `${topic.copy_finished_num}/${topic.copy_num}`
            
            return (
              <Card key={topic.id} className="hover:shadow-lg transition-shadow">
                <CardHeader className="pb-2">
                  <div className="flex justify-between items-start">
                    <CardTitle className="text-lg">
                      <Button 
                        variant="link" 
                        className="p-0 text-left font-semibold text-lg h-auto"
                        // onClick={() => window.open(`/topics/${topic.id}`, '_blank')}
                      >
                        {topic.name || 'N/A'}
                      </Button>
                    </CardTitle>
                    <div className="flex gap-1">
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Button 
                            variant="ghost" 
                            size="icon"
                            className="h-8 w-8"
                            onClick={() => handleEdit(topic)}
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                        </TooltipTrigger>
                        <TooltipContent>编辑</TooltipContent>
                      </Tooltip>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Button 
                            variant="ghost" 
                            size="icon"
                            className="h-8 w-8"
                            onClick={async () => {
                              const confirmWarning = window.confirm(
                                `警告：这将永久删除项目 "${topic.name}" 及其所有文案和脚本！\n` +
                                '此操作不可撤销，确定要继续吗？'
                              )
                              
                              if (!confirmWarning) {
                                toast({
                                  title: '删除取消',
                                  description: '用户取消删除操作',
                                  variant: 'destructive'
                                })
                                return
                              }

                              const projectName = window.prompt(`请输入项目名称 "${topic.name}" 以确认删除`)
                              if (projectName !== topic.name) {
                                toast({
                                  title: '删除取消',
                                  description: '项目名称不匹配',
                                  variant: 'destructive'
                                })
                                return
                              }

                              if (topic.id) {
                                await handleDelete(topic.id)
                              } else {
                                console.error('Cannot delete topic without ID')
                              }
                            }}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </TooltipTrigger>
                        <TooltipContent>删除</TooltipContent>
                      </Tooltip>
                    </div>
                  </div>
                </CardHeader>
                <CardContent className="space-y-2 text-sm">
                  <div className="flex items-center gap-2">
                    <span className="font-medium">目标:</span>
                    <span className="text-muted-foreground">
                      {topic.target ? 
                        topic.target.length > 50 ? 
                          `${topic.target.substring(0, 50)}...` : 
                          topic.target : 
                        'N/A'}
                    </span>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="font-medium">状态:</span>
                    <Badge variant="outline">{topic.status}</Badge>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="font-medium">创建时间:</span>
                    <span className="text-muted-foreground">{createdDate}</span>
                  </div>
                  <Link href={`/progress?topicid=${topic.id}`} className="flex items-center gap-2 hover:underline">
                    <span className="font-medium">进度:</span>
                    <Progress 
                      value={((topic.copy_finished_num || 0) / (topic.copy_num || 1)) * 100} 
                      className="h-2 w-24"
                    />
                    <span className="text-muted-foreground text-sm">{copyProgress}</span>
                  </Link>
                </CardContent>
              </Card>
            )
          })}
        </div>
      </div>
    </TooltipProvider>
  )
}


interface TopicFormProps {
  topic?: VmsTopic | null
  onCancel: () => void
  onSubmit: (topic: VmsTopic) => void
}

const TopicForm = ({ topic, onCancel, onSubmit }: TopicFormProps) => {
  const [formData, setFormData] = useState<VmsTopic>({
    id: topic?.id || '',
    name: topic?.name || '',
    target: topic?.target || '',
    status: topic?.status || 'To Do',
    copy_num: topic?.copy_num || 0,
    copy_finished_num: topic?.copy_finished_num || 0,
    cjsj: topic?.cjsj ? moment(topic.cjsj).toDate() : new Date(),
    user_id:topic?.user_id
  })

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: type === 'number' ? Number(value) : value
    }))
  }

  const handleStatusChange = (value: string) => {
    setFormData(prev => ({
      ...prev,
      status: value
    }))
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    onSubmit(formData)
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <label htmlFor="name" className="block mb-2">名称</label>
        <input
          id="name"
          name="name"
          type="text"
          value={formData.name}
          onChange={handleChange}
          className="w-full p-2 border rounded"
          required
        />
      </div>
      <div>
        <label htmlFor="target" className="block mb-2">目标</label>
        <input
          id="target"
          name="target"
          type="text"
          value={formData.target}
          onChange={handleChange}
          className="w-full p-2 border rounded"
          required
        />
      </div>
      <div>
        <label htmlFor="status" className="block mb-2">状态</label>
        <Select 
          value={formData.status} 
          onValueChange={handleStatusChange}
        >
          <SelectTrigger className="w-full">
            <SelectValue placeholder="To Do" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="To Do">To Do</SelectItem>
            <SelectItem value="In Progress">In Progress</SelectItem>
            <SelectItem value="Done">Done</SelectItem>
          </SelectContent>
        </Select>
      </div>
      <div className="flex justify-end gap-2">
        <Button
          type="button"
          variant="outline"
          onClick={onCancel}
        >
          取消
        </Button>
        <Button type="submit">
          {topic ? '更新' : '创建'}
        </Button>
      </div>
    </form>
  )
}
